import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateSpectrumDto, UpdateSpectrumDto, QuerySpectrumDto, QueryInfoSpectrumDto } from './dto/spectrum.dto';
import { SpectrumEntity } from './entities/spectrum.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class SpectrumService {
  constructor(
    @InjectRepository(SpectrumEntity)
    private readonly spectrumEntityRep: Repository<SpectrumEntity>,
  ) {}

  async create(createSpectrumDto: CreateSpectrumDto) {
    const res = await this.spectrumEntityRep.save(createSpectrumDto);
    return ResultData.ok(res);
  }

  async findAll(query: QuerySpectrumDto) {
    const entity = this.spectrumEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.childId)) {
      entity.andWhere('entity.childId = :childId', { childId: query.childId });
    }
    if (!isEmpty(query.emotionFlow)) {
      entity.andWhere('entity.emotionFlow = :emotionFlow', { emotionFlow: query.emotionFlow });
    }
    if (!isEmpty(query.selfExpression)) {
      entity.andWhere('entity.selfExpression = :selfExpression', { selfExpression: query.selfExpression });
    }
    if (!isEmpty(query.behaviorAttribution)) {
      entity.andWhere('entity.behaviorAttribution = :behaviorAttribution', { behaviorAttribution: query.behaviorAttribution });
    }
    if (!isEmpty(query.difficultyCoping)) {
      entity.andWhere('entity.difficultyCoping = :difficultyCoping', { difficultyCoping: query.difficultyCoping });
    }
    if (!isEmpty(query.interactionInitiative)) {
      entity.andWhere('entity.interactionInitiative = :interactionInitiative', { interactionInitiative: query.interactionInitiative });
    }
    if (!isEmpty(query.reportTags)) {
      entity.andWhere('entity.reportTags = :reportTags', { reportTags: query.reportTags });
    }
    if (!isEmpty(query.reportContent)) {
      entity.andWhere('entity.reportContent = :reportContent', { reportContent: query.reportContent });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select([
      'entity.id',
      'entity.childId',
      'entity.emotionFlow',
      'entity.selfExpression',
      'entity.behaviorAttribution',
      'entity.difficultyCoping',
      'entity.interactionInitiative',
      'entity.reportTags',
      'entity.reportContent',
    ]);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.spectrumEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    return ResultData.ok(res);
  }
  async findInfo(query: QueryInfoSpectrumDto) {
    // 参数验证和默认值设置
    if (!query.childId) {
      throw new Error('孩子ID不能为空');
    }
    const currentPage = query.currentPage || 1;
    const pageSize = 1; // 每次只查询一条记录
    const offset = (currentPage - 1) * pageSize;

    // 使用TypeORM查询构建器，与项目其他方法保持一致
    const queryBuilder = this.spectrumEntityRep.createQueryBuilder('spectrum');

    // 设置查询条件
    queryBuilder.where({
      childId: query.childId,
      delFlag: '0',
    });

    // 设置排序
    queryBuilder.orderBy('spectrum.createTime', 'DESC');

    // 并行执行查询（更高效）
    const [info, total] = await Promise.all([
      // 查询当前页的记录
      queryBuilder.skip(offset).take(pageSize).getMany(),
      // 查询总记录数
      queryBuilder.getCount(),
    ]);

    return ResultData.ok({
      info,
      total,
      currentPage,
    });
  }

  async update(updateSpectrumDto: UpdateSpectrumDto) {
    const res = await this.spectrumEntityRep.update({ id: updateSpectrumDto.id }, updateSpectrumDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(ids: number[]) {
    const res = await this.spectrumEntityRep.update(
      { id: In(ids) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }
}
